/******************************************************************************

        Filename (class)        :       Logger.cpp (Logger)
        Author                  :       Kuba Sejdak
        Last modification       :       29.03.2011
        Architecture			:		All
        Description             :       Simple class that provides interface to
        manage logging. Includes file handling and appending date and time info.

******************************************************************************/

#include "Logger.h"

QString getDateStr()
{
    return QDateTime::currentDateTime().toString("dd.MM.yyyy");
}

QString getTimeStr()
{
    return QDateTime::currentDateTime().toString("hh::mm::ss");
}

Logger::Logger()
{
    /* initialize data */
    maxFileSize = 100000;
    fileName = "";
    errorPreffix = "ERROR: ";

    /* create objects */
    file = new QFile;
    file->setFileName(fileName);
}

Logger::Logger(QString name)
{
    /* initialize data */
    maxFileSize = 100000;
    fileName = name;
    errorPreffix = "ERROR: ";

    /* create objects */
    file = new QFile;
    file->setFileName(fileName);
}

void Logger::checkFileSize()
{
    if(file->size() > maxFileSize)
        clearFile();
    else
        return;
}

void Logger::clearFile()
{
    file->resize(0);
}

void Logger::setFileName(QString name)
{
    fileName = name;
    file->setFileName(fileName);
}

void Logger::setFileNameDialog()
{
    fileName = QFileDialog::getOpenFileName();
    file->setFileName(fileName);
}

void Logger::setMaxFileSize(int size)
{
    maxFileSize = size;
}

void Logger::setErrorPreffix(QString preffix)
{
    errorPreffix = preffix;
}

LogState Logger::writeLog(QString message)
{
    if(file->fileName() == "")
        return FILE_NOT_SET;

    checkFileSize();

    if(!file->open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))
        return OPEN_FILE_ERROR;

    QTextStream out(file);
    QString logStr = getLog(message);
    out << logStr;

    file->close();
    if(file->isOpen())
        return CLOSE_FILE_ERROR;

    return DONE;
}

LogState Logger::writeErrorLog(QString message)
{
    if(file->fileName() == "")
        return FILE_NOT_SET;

    checkFileSize();

    if(!file->open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))
        return OPEN_FILE_ERROR;

    QTextStream out(file);
    QString logStr = getErrorLog(message);
    out << logStr;

    file->close();
    if(file->isOpen())
        return CLOSE_FILE_ERROR;

    return DONE;
}

QString Logger::getLog(QString message)
{
    QString logDate = "[" + getDateStr() + " - " + getTimeStr() + "] ";
    return logDate + message + "\n";
}

QString Logger::getErrorLog(QString message)
{
    QString logDate = "[" + getDateStr() + " - " + getTimeStr() + "] ";
    return logDate + errorPreffix + message + "\n";
}
